package org.steven.crm.app.api.processor.base;

import org.steven.crm.core.auth.UserSession;
import org.steven.crm.core.service.BaseService;

import java.util.Map;

public abstract class BaseUserCURDProcessor extends BaseUserReadOnlyProcessor {
	@Override
	public void startProcess() throws Exception {
	}
	
	@Override
	public void endProcess() throws Exception {
	}

	protected abstract BaseService getService();

	protected String[] getRemoveCreateColumnValue() {
		return null;
	}

	protected String[] getRemoveUpdateColumnValue() {
		return null;
	}

	/**
	 * 标准新增接口
	 * @throws Exception
	 */
	public void createAction() throws Exception {
		removeColumnValue(getRemoveCreateColumnValue());

		Map<String, String> data = getStringDatas();
		data.put("userId", UserSession.get().get("id"));

		Map<String, String> newData = getService().create(data);
		setObjectData(newData);
	}

	/**
	 * 标准更新接口
	 * @throws Exception
	 */
	public void updateAction() throws Exception {
		String id = getStringData("id");

		Map<String, String> srcData = getService().read(id);

		securityCheck(srcData);

		removeColumnValue(getRemoveUpdateColumnValue());

		Map<String, String> data = getStringDatas();
		data.remove("supplierId");
		data.remove("tenantId");

		Map<String, String> newData = getService().update(id, data);
		setObjectData(newData);
	}

	/**
	 * 标准新增/更新接口（根据是否传入id决定是新增还是更新）
	 * @throws Exception
	 */
	public void saveAction() throws Exception {
		if (getStringData("id").equals("")) {
			this.createAction();
		} else {
			this.updateAction();
		}
	}

	/**
	 * 标准删除接口
	 * @throws Exception
	 */
	public void deleteAction() throws Exception {
		String id = getStringData("id");
		Map<String, String> srcData = getService().read(id);

		securityCheck(srcData);

		getService().delete(id);
	}

	protected void removeColumnValue(String[] columns) {
		if (columns == null) {
			return;
		}
		Map<String, String> stringData = getStringDatas();
		for (String column : columns) {
			stringData.remove(column);
		}
	}
}